package com.hk.webapp.service.impl;

import com.hk.webapp.bean.SiteSetting;
import com.hk.webapp.dao.SiteSettingMapper;
import com.hk.webapp.vo.SiteSettingVo;
import com.hk.webapp.service.SiteSettingService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Objects;

@Service
@Transactional(readOnly = true)
public class SiteSettingServiceImpl implements SiteSettingService {

    @Resource
    private SiteSettingMapper siteSettingMapper;

    @Override
    public List<SiteSetting> getEntityList() {
        return siteSettingMapper.getEntityList();
    }

    @Override
    @Transactional
    public Integer updateValue(SiteSettingVo vo) {

        Field[] fields=vo.getClass().getDeclaredFields();
        int count=0;
        for (Field field:fields) {
            String key=field.getName();
            Object value=getFieldValueByName(field.getName(),vo);
            if (!Objects.isNull(value)){
                key=key.replaceAll("[A-Z]", "_$0").toLowerCase();
            }
            siteSettingMapper.updateValue(key,value==null?"":value.toString());
            count++;
        }
        return count;
    }
    /**
     * 根据属性名获取属性值
     * */
    private Object getFieldValueByName(String fieldName, Object o) {
        try {
            String firstLetter = fieldName.substring(0, 1).toUpperCase();
            String getter = "get" + firstLetter + fieldName.substring(1);
            Method method = o.getClass().getMethod(getter, new Class[] {});
            Object value = method.invoke(o, new Object[] {});
            return value;
        } catch (Exception e) {
            return null;
        }
    }
}
